#include "id_led.h"
// index = GPIOn_IOx = (n-1)*32 + x
// 例如蜂鸣器使用的引脚编号为：index = GPIO1_19 = (1-1)*32 +19 = 19。
// 又例如 GPIO4_IO20 的编号为：index = GPIO4_IO20 = (4-1)*32+20=116

#define GPIO_num    "3"

sem_t sem_led;

int id_led_init(void)
{
    int fd_led;
    /* 导出io口节点到用户空间*/
    if( access("/sys/class/gpio/gpio" GPIO_num, F_OK) != 0 ){
        fd_led = open("/sys/class/gpio/export", O_WRONLY);
        if( fd_led < 0 ){
            printf("id led export open error");
            // return -1;
            exit(-1);
        }
        if( write(fd_led, GPIO_num, sizeof(GPIO_num)) != sizeof(GPIO_num) ){
            printf("id led write export error");
            // return -1;
            exit(-1);
        }
    }
    /*设置io口为输出模式*/
    fd_led = open("/sys/class/gpio/gpio" GPIO_num "/direction", O_WRONLY);
    if( fd_led < 0 ){
        printf("id led direction open error");
        // return -1;
        exit(-1);
    }
    if( write(fd_led, "out", 3) != 3 ){
        printf("id led write direction error");
        // return -1;
        exit(-1);
    }
    /*设置io口电平*/
    fd_led = open("/sys/class/gpio/gpio" GPIO_num "/value", O_WRONLY);
    if( fd_led < 0 ){
        printf("id led value open error");
        // return -1;
        exit(-1);
    }
    if( write(fd_led, "1", 1) != 1){
        printf("set init vol id led error!\n ");
        exit(-1);
    }

    printf("id led program ready\n");
    sem_post(&sem_led);
    usleep(10*1000);
    while (1)
    {
        /* code */
        sem_wait(&sem_led);
        /* 开led */
        if( write(fd_led, "0", 1) != 1){
            if( write(fd_led, "0", 1) != 1){
                printf("set 0 id led error!\n ");
                exit(-1);
            }
        }
        usleep(20*1000);
        sem_wait(&sem_led);
        /* 关led */
        if( write(fd_led, "1", 1) != 1){
            if( write(fd_led, "1", 1) != 1){
                printf("set 1 id led error!\n ");
                exit(-1);
            }
        }
        usleep(20*1000);
    }
    
    
}


